import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import ElementUI from '../components/ElementUI.vue'
import Home from '../components/Home.vue'
import User from '../components/user/user.vue'
import Item from '../components/items/Item.vue'
import Welcome from '../components/Welcome.vue'
import ItemCat from '../components/items/ItemCat.vue'
import AddItem from '../components/items/addItem.vue'

//使用路由机制  通过children实现路由嵌套, redirect重定向
Vue.use(VueRouter)
const routes = [
  {path: '/', redirect: '/login'},
  {path: '/login', component: Login},
  {path: '/elementUI', component: ElementUI},
  //children组件的跳转 在home组件内部进行填充
  {path: '/home', component: Home,  redirect: '/welcome', children:[
      {path: '/welcome', component: Welcome},
      {path: '/user', component: User},
      {path: '/item', component: Item},
      {path: '/itemCat', component: ItemCat},
      {path: '/item/addItem', component: AddItem}
    ]}
]

//配置路由对象
const router = new VueRouter({
  routes
})

/* 配置路由导航守卫 控制权限
  1.to 要跳转的网址
  2.from 请求从哪里来
  3.next 回调函数  放行/跳转
 */
router.beforeEach((to,from,next) => {
  //1.如果用户访问 /login  请求应该放行 终止程序
  if(to.path === '/login') {
    return next()
  }

  //2.如果用户访问不是login 则需要校验是否登录 检查是否有token
  let token = window.sessionStorage.getItem('token')
  if(token !== null && token.length > 0){
    return next()
  }else {
    //没有token 应该跳转到登录页面 "/login"
    return next("/login")
  }

  //if(token) if的一种简化写法 解析: 如果token不为null
  //if(!token)  解析: token为null
})






export default router
